package com.xo.xodemo.controller.file;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.xo.xodemo.service.FileService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

@Controller
@RequestMapping("/file")
public class FileController {
    @Autowired
    FileService fileService;
    @RequestMapping("/img")
    public void code(@Param("imgaddress") String imgaddress,HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletOutputStream outputStream = null;
        FileInputStream inputStream = null;
        File file=fileService.getimage(imgaddress);
        response.setHeader("Content-Length", file.length() + "");
        inputStream = new FileInputStream(file);
        outputStream = response.getOutputStream();
        String rangeString = request.getHeader("Range");
        if(null!=rangeString){
            // range 值
            long rangeStart = Long.parseLong(rangeString.substring(rangeString.indexOf("=") + 1, rangeString.indexOf("-")));
            // range范围是从0个字节开始，所以结束位置下标是文件长度-1
            long rangeEnd = file.length() - 1;
            response.setHeader("Content-Range", "bytes " + rangeStart + "-" + rangeEnd + "/" + file.length());

            // 告知video / audio标签可以接受范围单位，这个头必须传递
            response.setHeader("Accept-Ranges", "bytes");
        }


        //读取文件流
        int len = 0;
        byte[] buffer = new byte[1024 * 1024];
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        outputStream.flush();


    }
}
